<!-- 基础信息 -->
<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="140px">
    <el-row :gutter="24">
      <el-col v-bind="grid">
        <el-form-item :label="$t('shangPinMingCheng')+'：'" prop="storeName">
          <el-input v-model="formData.storeName" :placeholder="$t('qingShuRuShangPinMingCheng')" maxlength="200" clearable show-word-limit />
        </el-form-item>
      </el-col>
      <el-col v-bind="grid">
        <el-form-item :label="$t('shangPinId')+'：'" prop="skuCode">
          <el-input v-model="formData.skuCode" :disabled="isDisabled" clearable :placeholder="$t('qingShuRuShangPinId')" maxlength="80" />
        </el-form-item>
      </el-col>
      <el-col v-bind="grid">
        <el-form-item :label="$t('shangPinFenLei')+'：'" prop="categoryId">
          <el-cascader
            :key="key"
            v-model="formData.categoryId"
            :options="translateNameProductClassify"
            :props="categoryProps"
            filterable
            clearable
            class="selWidth"
            :show-all-levels="false"
          />
        </el-form-item>
      </el-col>
      <el-col v-bind="grid">
        <el-form-item :label="$t('pinPai') + '：'" prop="brandId">
          <el-select
            v-model="formData.brandId"
            v-selectLoadMore="selectLoadMore"
            class="selWidth"
            clearable
            filterable
            remote
            allow-create
            :remote-method="remoteMethod"
            :placeholder="$t('tishi15')"
            default-first-option
            popper-class="custom-popper"
            maxlength="50"
            @change="brandChange"
          >
            <el-option v-for="user in brandList" :key="user.id" :label="user.name" :value="user.id" :disabled="user.disabled" />
          </el-select>

        </el-form-item>
      </el-col>
      <el-col v-bind="grid">
        <el-form-item :label="$t('zheKouJia')+'：'" prop="price">
          <el-input-number v-model.number="formData.price" type="number" :min="0.01" :max="99999999.99" :precision="2" controls-position="right" :placeholder="$t('qingShuRuZheKouJia')" />
        </el-form-item>
      </el-col>
      <el-col v-bind="grid">
        <el-form-item :label="$t('yuanJia')+'：'" prop="originalPrice">
          <el-input-number v-model="formData.originalPrice" type="number" :min="0.01" :max="99999999.99" :precision="2" controls-position="right" :placeholder="$t('qingShuRuYuanJia')" />
        </el-form-item>
      </el-col>
      <el-col v-bind="grid">
        <el-form-item label="HSCODE:" prop="hsCode">
          <el-input v-model="formData.hsCode" :placeholder="$t('qingShuRuHscode')" maxlength="255" clearable />
        </el-form-item>
      </el-col>
      <el-col v-bind="grid">
        <el-form-item :label="$t('shiFouDaiDian') + '：'" prop="electricityFlag">
          <el-switch
            v-model="formData.electricityFlag"
            active-value="Y"
            inactive-value="N"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :label="$t('shangPinGuiGe') + '：'" props="specType">
          <el-radio-group v-model="formData.specType">
            <el-radio :label="false" class="radio">{{ $t('danGuiGe') }}</el-radio>
            <!-- <el-radio :label="true">{{ $t('duoGuiGe') }}</el-radio> -->
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :label="$t('shangPinChiCun')+'(CM)：'" prop="skuLength">
          <el-input-number v-model="formData.skuLength" type="number" :min="0.01" :max="99999999.99" :precision="2" controls-position="right" :placeholder="$t('qingShuRuChangDu')" />
          <span class="divide">*</span>
          <el-input-number v-model="formData.skuWidth" type="number" :min="0.01" :max="99999999.99" :precision="2" controls-position="right" :placeholder="$t('qingShuRuKuanDu')" />
          <span class="divide">*</span>
          <el-input-number v-model="formData.skuHeight" type="number" :min="0.01" :max="99999999.99" :precision="2" controls-position="right" :placeholder="$t('qingShuRuGaoDu')" />
        </el-form-item>
      </el-col>
      <el-col v-bind="grid">
        <el-form-item :label="$t('zhongLiang')+'(KG)：'" prop="skuWeight">
          <el-input-number v-model="formData.skuWeight" type="number" :min="0.01" :max="99999999.99" :precision="2" controls-position="right" :placeholder="$t('qingShuRuZhongLiang')" />
        </el-form-item>
      </el-col>
      <el-col v-bind="grid">
        <el-form-item :label="$t('yanSe') + '：'" prop="skuColor">
          <el-input v-model.number="formData.skuColor" :placeholder="$t('qingShuRuYanSe')" maxlength="50" clearable />
        </el-form-item>
      </el-col>
      <el-col v-bind="grid">
        <el-form-item :label="$t('xingHao') + '：'" prop="skuModel">
          <el-input v-model="formData.skuModel" :placeholder="$t('qingShuRuXingHao')" maxlength="50" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :label="$t('shangPinZhuTu') + '：'" prop="image">
          <div class="upLoadPicBox acea-row" @click="modalPicTap('1','image')">
            <div v-if="formData.image" class="pictrue"><img :src="formData.image"></div>
            <div v-else class="upLoad">
              <i class="el-icon-camera cameraIconfont" />
            </div>
            <span>{{ $t('tishi16') }}</span>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :label="$t('shangPinZhanShiTu') + '：'" prop="flatPattern">
          <div class="upLoadPicBox acea-row" @click="modalPicTap('1','flatPattern')">
            <div v-if="formData.flatPattern" class="pictrue"><img :src="formData.flatPattern"></div>
            <div v-else class="upLoad">
              <i class="el-icon-camera cameraIconfont" />
            </div>
            <span>{{ $t('tishi16') }}</span>
          </div>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item :label="$t('shangPinLunBoTu') + '：'" prop="sliderImage">
          <div class="upLoadPicBox acea-row" @click="modalPicTap('1','sliderImage')">
            <div v-if="formData.sliderImage" class="pictrue"><img :src="formData.sliderImage"></div>
            <div v-else class="upLoad">
              <i class="el-icon-camera cameraIconfont" />
            </div>
            <span>{{ $t('tishi16') }}</span>
          </div>
        </el-form-item>
      </el-col>
      <el-col v-bind="grid">
        <el-form-item :label="$t('kuCunShu') + '：'" prop="stock">
          <el-input-number v-model="formData.stock" type="number" :precision="0" :min="0" :max="99999999" controls-position="right" :placeholder="$t('qingShuRuKuCunShu')" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-col :span="24">
      <el-form-item :label="$t('cnShangPinXiangQing') + '：'" prop="storeInfo">
        <el-input v-model="formData.storeInfo" placeholder="请输入商品详情" type="textarea" :autosize="{ minRows: 4, maxRows: 8}" maxlength="500" show-word-limit />
      </el-form-item>
    </el-col>
    <!-- <el-form-item :label="$t('cnShangPinXiangQing') + '：'" prop="content">
      <Tinymce v-model="formData.content" />
    </el-form-item> -->
  </el-form>
</template>
<script>
import Tinymce from '@/components/Tinymce/index'

import { mapGetters } from 'vuex'
import { brandListApi } from '@/api/store'
const reg = /^[^\u4e00-\u9fa5]+$/
export default {
  components: { Tinymce },
  directives: {
    // 计算是否滚动到最下面
    selectLoadMore: {
      bind(el, binding) {
        // 获取element-ui定义好的scroll盒子
        const SELECTWRAP_DOM = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
        SELECTWRAP_DOM.addEventListener('scroll', function() {
          if (this.scrollHeight - this.scrollTop < this.clientHeight + 1) {
            binding.value()
          }
        })
      }
    }
  },
  data() {
    const sizeValid = (rule, value, callback) => {
      if (!this.formData.skuLength) {
        callback(new Error(this.$t('qingShuRuChangDu')))
      } else if (!this.formData.skuWidth) {
        callback(new Error(this.$t('qingShuRuKuanDu')))
      } else if (!this.formData.skuHeight) {
        callback(new Error(this.$t('qingShuRuGaoDu')))
      } else {
        callback()
      }
    }
    return {
      key: 0,
      grid: {
        xl: 12,
        lg: 12,
        md: 12,
        sm: 24,
        xs: 24
      },
      isDisabled: false,
      // 分类级联配置
      categoryProps: {
        children: 'childList',
        label: 'translateName',
        value: 'id',
        multiple: false,
        emitPath: false
      },
      // 品牌搜索条件
      loading: true,
      search: {
        limit: 10,
        page: 1,
        name: '',
        isShow: 1
      },
      // 品牌列表
      brandList: [],
      dragging: false,
      formData: {
        'storeName': '', // 商品名称
        'skuCode': '', // 商品id
        'categoryId': null, // 商品分类
        'brandId': null, // 品牌
        'brandName': '', // brandId为空时必填
        'price': '', // 折扣价
        'originalPrice': '', // 原价
        'hsCode': '', // HSCode
        'electricityFlag': 'N', // 是否带电
        'storeInfo': '', // 商品简介
        'specType': false, // 默认值,单规格
        'skuLength': '', // 长度
        'skuWidth': '', // 宽度
        'skuHeight': '', // 高度
        'skuWeight': '', // 重量
        'skuColor': '', // 颜色
        'skuModel': '', // 型号
        'image': '', // 主图
        'flatPattern': '', // 展示图
        'sliderImage': '', // 轮播图
        'stock': '', // 库存数
        customBrand: false // 判断是否为自定义品牌
        // content: ''
      },
      rules: {
        'storeName': [
          { required: true, message: this.$t('qingShuRuShangPinMingCheng'), trigger: 'blur' },
          { trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }
        ], // 商品名称
        'skuCode': [
          { required: true, message: this.$t('qingShuRuShangPinId'), trigger: 'blur' },
          { trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }
        ], // 商品id
        'categoryId': { required: true, message: this.$t('qingXuanZeShangPinFenLei'), trigger: 'change' }, // 商品分类
        'brandId': [
          { required: true, message: this.$t('qingXuanZePinPai'), trigger: 'change' },
          { trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }
        ], // 品牌
        'price': [{ required: true, message: this.$t('qingShuRuZheKouJia'), trigger: ['blur', 'change'] }], // 折扣价
        'originalPrice': [{ required: true, message: this.$t('qingShuRuYuanJia'), trigger: ['blur', 'change'] }], // 原价
        'skuLength': [{ required: true, validator: sizeValid, trigger: ['blur', 'change'] }], // 长度
        'skuWeight': [{ required: true, message: this.$t('qingShuRuZhongLiang'), trigger: ['blur', 'change'] }], // 重量
        'skuColor': [
          { required: true, message: this.$t('qingShuRuYanSe'), trigger: 'blur' },
          { trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }
        ], // 颜色
        'skuModel': [
          { required: true, message: this.$t('qingShuRuXingHao'), trigger: 'blur' },
          { trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }
        ], // 型号
        'image': { required: true, message: this.$t('qingShangChuanZhuTu'), trigger: 'blur' }, // 主图
        'flatPattern': { required: true, message: this.$t('qingShangChuanZhanShiTu'), trigger: 'blur' }, // 展示图
        'sliderImage': { required: true, message: this.$t('qingShangChuanLunBoTu'), trigger: 'blur' }, // 轮播图
        'stock': { required: true, message: this.$t('qingShuRuKuCunShu'), trigger: ['blur', 'change'] }, // 库存数
        'hsCode': [{ trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }],
        // 'storeInfo': [{ trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }],
        storeInfo: [
          { required: true, message: '请输入商品详情', trigger: 'blur' },
          { trigger: ['blur', 'change'], message: this.$t('buNengBaoHanZhongWen'), pattern: reg }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['adminProductClassify', 'translateNameMerProductClassify', 'productBrand', 'translateNameProductClassify'])
  },
  mounted() {
    this.getbrandList()
  },
  methods: {
    // 下拉加载更多
    selectLoadMore() {
      if (this.search.limit < 10) {
        this.search.limit = 10
      }
      this.search.limit = this.search.limit + 5
      if (this.search.limit > this.totalPage) return
      this.getbrandList() // 请求接口
    },
    // 远程搜索
    remoteMethod(query) {
      this.loading = true
      this.search.name = query
      this.search.limit = 10
      this.brandList = []
      setTimeout(() => {
        this.loading = false
        this.getbrandList() // 请求接口
      }, 200)
    },
    initBrandList() {
      this.getbrandList().then(res => {
        const obj = res.find(item => item.id === this.formData.brandId)
        if (!obj) {
          this.brandList.push({
            id: this.formData.brandId,
            name: this.formData.brandName
          })
        }
      })
    },
    // 品牌列表
    getbrandList() {
      // this.search.cid = this.formData.categoryId
      return new Promise((resolve, reject) => {
        brandListApi(this.search).then((res) => {
        // this.brandList = res
          if (!res.list.length) {
          // this.$message.warning(this.$t('ciFenLeiXiaMianWuPinPaiQingLianXiGuanLiYuanTianJiaCiFenLeiXiaDePinPai'))
            // this.brandList = [
            //   { name: '无此品牌，选择后将自动添加', id: undefined, disabled: true }
            // ]
          } else {
            this.totalPage = res.total
            this.brandList = res.list
            resolve(res.list)
          }
        })
      })
    },
    brandChange() {
      if (this.formData.brandId) {
        const obj = this.brandList.find(it => it.id === this.formData.brandId)
        if (obj) {
          this.formData.brandName = obj.name || this.formData.brandId
          this.formData.customBrand = false
        } else {
          this.formData.customBrand = true
          this.formData.brandName = this.formData.brandId
          // 限制长度为50
          if (this.formData.brandName.length > 50) {
            this.formData.brandName = this.formData.brandName.slice(0, 50)
          }
        }
      } else {
        this.formData.customBrand = false
        this.formData.brandName = ''
        this.search.name = ''
        this.getbrandList()
      }
    },
    // 移动
    handleDragStart(e, item) {
      if (!this.isDisabled) this.dragging = item
    },
    handleDragEnd(e, item) {
      if (!this.isDisabled) this.dragging = null
    },
    handleDragOver(e) {
      if (!this.isDisabled) e.dataTransfer.dropEffect = 'move'
    },
    handleDragEnter(e, item) {
      if (!this.isDisabled) {
        e.dataTransfer.effectAllowed = 'move'
        if (item === this.dragging) {
          return
        }
        const newItems = [...this.formData.sliderImage]
        const src = newItems.indexOf(this.dragging)
        const dst = newItems.indexOf(item)
        newItems.splice(dst, 0, ...newItems.splice(src, 1))
        this.formData.sliderImage = newItems
      }
    },
    handleRemove(i) {
      this.formData.sliderImage.splice(i, 1)
    },
    // 点击商品图
    modalPicTap(isMore, modelName) {
      this.$modalUpload(
        (img) => {
          this.formData[modelName] = img[0].sattDir
          // var bt = new Image()
          // bt.onload = () => {
          //   var width = bt.width
          //   var height = bt.height
          //   console.log(width)
          //   console.log(height)
          //   if ((width >= 500 && width <= 2000) && (height >= 500 && height <= 2000)) {
          //     if (isMore === '1') {
          //       this.formData[modelName] = img[0].sattDir
          //     }
          //   } else {
          //     this.$message({
          //       message: '尺寸不符合',
          //       type: 'error'
          //     })
          //   }
          // }
          // bt.src = img[0].sattDir
        },
        isMore,
        'content'
      )
    },
    submitForm() {
      return new Promise((resolve, reject) => {
        this.$refs['formRef'].validate((valid) => {
          if (valid) {
            resolve()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      })
    }
  }
}
</script>
<style scoped lang="scss">
.selWidth{
  width: 100%;
}
.divide{
  padding: 0 10px;
}

.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 10px;
  position: relative;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }

  video {
    width: 100%;
    height: 100%;
  }
}

.custom-popper .el-scrollbar__view .el-select-dropdown__item.is-new {
  font-weight: bold;
  background-color: #e3e3e3;
}

</style>
